package com.ssy.wireless.api.service;

import com.ssy.wireless.entity.ApDevice;
import com.ssy.wireless.entity.UserAuth;
import com.ssy.wireless.mapper.ApDeviceMapper;
import com.ssy.wireless.mapper.UserAuthMapper;
import com.ssy.wireless.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * Created by cofey on 16/11/21.
 */
@Service
@Transactional(readOnly = true)
public class ApiUserAuthService {
    @Autowired
    private UserAuthMapper userAuthMapper;

    @Autowired
    private ApDeviceMapper apDeviceMapper;

    @Transactional
    public void insert(UserAuth userAuth) {
        Assert.notNull(userAuth, "用户认证对象不能为空");
        Assert.isTrue(StringUtils.hasLength(userAuth.getApIndex()), "AP索引不能为空");
        Assert.isTrue(StringUtils.hasLength(userAuth.getMobile()), "用户账号不能为空");
        ApDevice apDevice = apDeviceMapper.selectByApIndex(userAuth.getApIndex());
        Assert.notNull(apDevice, "当前AP索引[" + userAuth.getApIndex() + "]不存在");
        userAuth.setApDeviceId(apDevice.getId());
        userAuth.setHotspotId(apDevice.getHotspotId());
        userAuth.setEntId(apDevice.getEntId());
        userAuth.setAuthTime(new Date());
        userAuth.setExpireTime(DateUtils.monthAdd(userAuth.getAuthTime(),1));
        userAuthMapper.insert(userAuth);

        apDeviceMapper.updateDeviceCount(userAuth.getApDeviceId(),userAuth.getHotspotId());
    }
}
